﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using PBO.Sql;

namespace PBO.Data.SQLite
{
    /// <summary>
    /// DbHelperSQLite
    /// </summary>
    public abstract class DALModel<T> where T : GameElement
    {
        protected static IDBUtility DBUtility = SQLiteHelper.DbHelperSQLite;

        #region abstract

        protected abstract string GetTableName();
        protected abstract T DataRowToModel(DataRow dr);
        //public abstract T GetModel(int id);
        protected virtual string GetSqlFields()
        {
            return "*";
        }

        #endregion

        protected T GetSingle(string sql)
        {
            var dt = DBUtility.ExecuteDataTable(sql);
            return (dt != null && dt.Rows.Count > 0) ? DataRowToModel(dt.Rows[0]) : null;
        }

        protected List<T> GetModel(string where = "1=1")
        {
            var dt = GetDataTable(where);
            var list = from DataRow dr in dt.Rows select DataRowToModel(dr);
            return list.ToList();
        }

        protected DataTable GetDataTable(string where = "1=1")
        {
            string sql = "select " + GetSqlFields() + " from " + GetTableName() + " where " + where;
            var dt = DBUtility.ExecuteDataTable(sql);
            return dt;
        }
    }
}
